/*
 * Implementation of QBigHuge.
 *
 * Fetch synonyms from Big Huge Labs.
 */
#include <QtGui>
#include <QtNetwork>    // network module
#include <QtXml>        // xml module
#include "qbighuge.h"

// constructor
QBigHuge::QBigHuge() {}

// retrieve words from remote database
void QBigHuge::fetchSynonyms(const QString& word) {
	// create network manager
	QNetworkAccessManager *manager = new QNetworkAccessManager(this);
	// hook us up to be notified of download completion
	connect(manager, SIGNAL(finished(QNetworkReply*)),
		this, SLOT(finished(QNetworkReply*)));
	// use 'get' method on remote resource. finished() will be invoked

	// http://words.bighugelabs.com/api/2/your-api-key/love/xml
	// construct url
	QString url = BIGHUGE_API_URL;
	url += BIGHUGE_API_KEY;
	url += word;
	url += BIGHUGE_API_FORMAT;
#ifdef  NO_INTERNET
       // uct has internet issues. use offline sample
        manager->get(QNetworkRequest(QUrl(BIGHUGE_SAMPLE_FILE)));
#else
        manager->get(QNetworkRequest(QUrl(url)));
#endif
}

// download has completed
void QBigHuge::finished(QNetworkReply* reply) {
    if (QNetworkReply::NoError == reply->error()) {
        // QNetworkReply inherits from QIODevice and can
        // therefore be used like a stream.

        // parse the XML response
        QDomDocument doc; // DOM document

        // 'out' parameters which indicate parsing errors
        QString errorStr;
        int errorLine;
        int errorColumn;

        // setContent() accepts an IODevice, like QNetworkReply.
        // notice lowercase FALSE -- no xml reader
        if (doc.setContent(reply, false, &errorStr, &errorLine, &errorColumn)) {
            // get root node
            QDomElement root = doc.documentElement();
            // get all word nodes
            // first 'words' tag, then 'w' tag
            // note QDomNodeList collection type
            QDomNodeList nodes = root.elementsByTagName("w");
            // the string list which will be sent on success
            QStringList synonyms;
            for (unsigned int i = 0; i < nodes.length(); i++) {
                // add item to string list
                synonyms << nodes.item(i).firstChild().nodeValue();
            }
            // send the synonyms via a signal
            emit synonymsReceived(synonyms);
        } else {
            // xml parsing error.
            // assemble error string
            QString msg = errorStr + "\n";
            msg += "Line: ";
            msg += QString::number(errorLine);
            msg += " Column: ";
            msg += QString::number(errorColumn);
            // send error signal
            emit error(QBigHuge::XmlError, msg);
        }
    } else {
        // network error
        QString msg = reply->errorString();
        msg += "\n\nPlease check your network settings.";
        // send error signal
        emit error(QBigHuge::NetworkError, msg);
    }
}
